﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace GACore.InputArgs
{
	public class Persistence
	{
		private string filename;

		public delegate void AddIndividualPreferences(XElement root, ref Dictionary<string, object> individualPreferenceList);

		private Dictionary<string, object> individualPreferences = new Dictionary<string, object>();
		public Dictionary<string, object> IndividualPreferences
		{
			get { return individualPreferences; }
			set { individualPreferences = value; }
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="Persistence"/> class.
		/// </summary>
		/// <param name="type">The type.</param>
		public Persistence(string filename)
		{
			this.filename = filename;
		}

		public Preferences Load(AddIndividualPreferences indPreferences)
		{
			if (File.Exists(filename))
			{
				var root = LoadXMLDocument();

				if (indPreferences != null)
				{
					indPreferences(root, ref individualPreferences);
				}

				switch ((string)root.Element("VectorType"))
				{
					case "int":
						return new Parser<int>().GetPreferences(root);
					case "double":
						return new Parser<double>().GetPreferences(root);
					case "bool":
						return new Parser<bool>().GetPreferences(root);
					default:
						throw new ArgumentException("Es wurde kein gültiger Vektortyp angegeben.");
				}
			}
			throw new FileLoadException("Die Datei konnte nicht geladen werden.");
		}

		private XElement LoadXMLDocument()
		{
			try
			{
				return XDocument.Load(filename).Root;
			}
			catch
			{
				throw new FileLoadException("Die angegebene Datei ist kein gültiges XML-Dokument.");
			}
		}

		public void Persist(Preferences preferences)
		{
			XmlSerializer x = new XmlSerializer(typeof(Preferences));
			StreamWriter writer = new StreamWriter(filename, false);
			x.Serialize(writer, preferences);
			writer.Close();
		}

	}
}
